package com.chebaohui.iqs.service.impl.deal.taiping;

import org.jdom.Element;

import com.chebaohui.iqs.config.ResultCode;

/**
 * 直连接口共有类
 * 
 * @author xielonghai
 *
 */
public class DirectTp {

	/**
	 * 太平直连接口请求以及处理<公共方法>
	 * 
	 * @param value
	 *            接口描述
	 * @param request
	 *            请求xml
	 * @param key
	 *            返回xml获取key
	 * @return
	 */
	public static ResTaiPing request(String value, String url, String request, String[] key) {
		String response = null;
		try {
			response = TPPost.postTP(url, request);

			value+="\n"+"请求地址:" + url;
			value+="\n"+"请求地址xml:" + request;
			value +="\n"+ "请求返回结果:" + response;

		} catch (Exception e) {
			value += "\n" + url + "请求异常:" + e.getMessage();
			return new ResTaiPing(ResultCode.N02, value, "HTTP请求" + url + "异常:" + e.getMessage());
		}

		return responseDeal(value, response, key);
	}

	/**
	 * 返回报文处理
	 * 
	 * @param response
	 *            返回报文
	 * @return
	 */
	private static ResTaiPing responseDeal(String value, String response, String[] key) {
		value += "\n" + "处理返回报文开始--";
		try {
			/** xml解析 **/
			Element el = XMLTool.toElement(response);
			/** head---请求返回报文判断 **/
			ResTaiPing deal = XMLTool.responsejudge(el);
			value += "\n" + "报文<head>结果处理结束";// + JSONObject.toJSONString(deal);
			if (!deal.isState()) {
				deal.setMsg(value);
				return deal;
			}

			/** 提取数据 **/
			ResTaiPing res = XMLTool.responseBody(el, key);
			res.setHead(deal.getResult());

			value += "\n" + "报文<body>结果处理结束";// + JSONObject.toJSONString(res);
			
			if(!res.isState())
				value+="\n" +"报文处理中错误:"+res.getMsg();
			
			res.setMsg(value);
			return res;
		} catch (Exception e) {
			value += "\n" +"报文处理异常:" + e.getMessage();
			return new ResTaiPing(ResultCode.N02, value, "报文处理异常:" + e.getMessage());
		}
	}
}
